package com.iflytek.iot.common.log.log2kafka.log.appender;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import com.iflytek.iot.common.log.log2kafka.config.LogConfig;
import com.iflytek.iot.common.log.log2kafka.log.Log2kafkaQueue;
import com.iflytek.iot.common.log.log2kafka.model.LogModel;

/**
 * @author taoyang13
 * @version 1.0
 * @description 日志动态打印appender
 * @date 2021/1/11 10:35:19
 */
public class MyOutputAppender extends ConsoleAppender {

    @Override
    protected void append(Object eventObject) {

        if(LogConfig.isOutputLog()){
            super.append(eventObject);
        }

        LoggingEvent loggingEvent = (LoggingEvent) eventObject;
        LogModel logBean = new LogModel()
                .setTName(loggingEvent.getThreadName())
                .setTimestamp(String.valueOf(loggingEvent.getTimeStamp()))
                .setLevel(loggingEvent.getLevel().levelStr)
                .setClassName(loggingEvent.getLoggerName())
                .setTraceId(loggingEvent.getMDCPropertyMap().get("traceId"))
                .setMessage(loggingEvent.getFormattedMessage());
        if (filter(logBean)) {
            Log2kafkaQueue.add(logBean);
        } else {
            Log2kafkaQueue.incrementIgnore();
        }
    }

    private boolean filter(LogModel logBean) {
        String className = logBean.getClassName();
        if ("logcalLogger".equals(className) || "errLogger".equals(className)) {
            // flume日志丢弃
            return false;
        }
        return true;
    }
}
